package com.zhisuo.apicenter.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhisuo.apicenter.Constants;
import com.zhisuo.apicenter.model.*;
import com.zhisuo.apicenter.service.ApiService;
import com.zhisuo.apicenter.service.ExpressManService;
import com.zhisuo.apicenter.service.UserManService;
import com.zhisuo.apicenter.util.DateUtil;
import com.zhisuo.apicenter.util.SendSmsUtil;
import com.zhisuo.apicenter.util.StringUtil;
import com.zhisuo.apicenter.util.TcpUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;



/**
 * 派件员相关操作
 */
@Controller
@RequestMapping(value = "/expressman")
public class ExpressManController {

    private static final Logger log = LoggerFactory.getLogger(ExpressManController.class);

    private ApiService apiService;

    @Autowired
    public void setApiService(ApiService apiService) {
        this.apiService = apiService;
    }

    private ExpressManService expressManService;

    @Autowired
    public void setExpressManService(ExpressManService expressManService) {
        this.expressManService = expressManService;
    }

    private UserManService userManService;

    @Autowired
    public void setUserManService(UserManService userManService) {
        this.userManService = userManService;
    }


    /**
     * 快递员获取派件数量
     */
    @RequestMapping(value = "/getSellerSendOrderNumByUserId")
    public void getSellerSendOrderNumByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getSellerSendOrderNumByUserId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");

        Integer orderhasreciptnum=0;
        orderhasreciptnum =userManService.getHasSellerSendOrderNumByUserId(userid);
        JSONObject datajson=new JSONObject();
        datajson.put("orderhasreciptnum",orderhasreciptnum);
        resultObj.put("error_code",0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data",datajson);
        responseData(resultObj.toString(), resp);
    }

    /**
     * 快递员是扫码取件
     */
    @RequestMapping(value = "/getUserSendOrderByCarIdId")
    public void getReceiptOrderByCarIdId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getReceiptOrderByCarIdId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");
        String sn = jsonObject.getString("sn");

        ZhiSuoCar car=expressManService.getCarByQrcode(sn);

        if(car==null){
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "二维码已失效，请重新扫码");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }

        List<SendOrder> listorder=userManService.getUserSendOrderIdByCarIdStatus(car.getId()+"");

        if(listorder != null && listorder.size()>0 ){


            //直接打开门
            //下发开箱指令
            List<ZhiSuoCarBox> listZhiSuoCarBox=expressManService.getListZhiSuoCarBoxByCarId(car.getId()+"");
            //获取TCP服务器地址
            String tcp_url=apiService.getTcpUrlByTcpCenterUrl("tcp_center_url");

            String tcpresult= TcpUtil.openSendOrderManyDoor(car,listorder,listZhiSuoCarBox,tcp_url);

            if(StringUtils.isNotEmpty(tcpresult)){
                JSONObject tcpresultjson=JSONObject.parseObject(tcpresult);
                String tcpresultjsonerrorCode=tcpresultjson.getString("errorCode");
                if(tcpresultjsonerrorCode.equals("1")){
                    responseErrorData("开门失败，请再试一次", resp);
                    return;
                }
            }else{
                responseErrorData("开门失败，请再试一次", resp);
                return;
            }



            JSONObject oneboxjson=null;
            JSONArray opendoorarray=new JSONArray();
            for(ZhiSuoCarBox carbox:listZhiSuoCarBox){
                oneboxjson=new JSONObject();
                Boolean flag=false;
                for(SendOrder order:listorder){
                    if(order.getBoxcode().equals(carbox.getName())){
                        flag=true;
                        break;
                    }else{
                        flag=false;
                    }
                }

                if(flag){
                    oneboxjson.put("code",carbox.getName());
                    oneboxjson.put("isopen","1");
                    oneboxjson.put("pos",carbox.getPos());
                }else{

                    oneboxjson.put("code",carbox.getName());
                    oneboxjson.put("isopen","0");
                    oneboxjson.put("pos",carbox.getPos());
                }
                opendoorarray.add(oneboxjson);
            }



            for(SendOrder order:listorder){

                userManService.updateSendOrderByReceiptcode(order.getId()+"",userid);
                //更新箱子状态
                expressManService.updateCarBoxStatusByCode(order.getBoxcode(),order.getCarid()+"");

            }




            resultObj.put("error_code",0);
            resultObj.put("error_msg", "取件成功，关好仓门");
            resultObj.put("data",opendoorarray);

        }else{
            //取件码开门
            resultObj.put("error_code",2);
            resultObj.put("error_msg", "该车无快件");
            resultObj.put("data",car.getId());

        }


        responseData(resultObj.toString(), resp);
    }

    /**
     * 根据派件单ID获取派件详情
     */
    @RequestMapping(value = "/getDeliveryOrderDetailById")
    public void getDeliveryOrderDetailById(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getDeliveryOrderDetailById-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String orderid = jsonObject.getString("orderid");


        DeliveryOrder order = userManService.getDeliveryOrderById(orderid);


        JSONObject jo = new JSONObject();

        ZhiSuoCar car = expressManService.getCarByCarId(order.getCarid());
        String parkareaid = expressManService.getParkareaidByCarId(car.getId());
        String parkAreaName = expressManService.getParkAreaNameById(parkareaid);
        jo.put("carid", car.getId());
        jo.put("carname", car.getName());
        jo.put("parkareaname", parkAreaName);
        jo.put("boxname", order.getBoxcode());
        jo.put("paymentcode", order.getPaymentcode());
        jo.put("create_time", order.getCreate_time());
        jo.put("paymnetcompany", order.getPaymentcompany());
        jo.put("orderid", order.getId());
        jo.put("receiptmobile", order.getReceiptusermobile());
        jo.put("customermobile", "400-100-100");

        ZhiSuoCarStatus carstatus = expressManService.getCarStatusByCarVin(car.getSn());
        if (carstatus != null) {
            jo.put("lng", carstatus.getPositionlon());
            jo.put("lat", carstatus.getPositionlat());
            jo.put("heading", carstatus.getPositionheading());
            jo.put("speedvalue", carstatus.getSpeedvalue());
            jo.put("speedunit", carstatus.getSpeedunit());
            if(StringUtils.isNotEmpty(carstatus.getPositionstop())){
                if(carstatus.getPositionstop().equals(car.getHomestation())){
                    jo.put("ishomestation",1);
                }else{
                    jo.put("ishomestation",0);
                }
            }else{
                jo.put("ishomestation",0);
            }
        } else {
            jo.put("lng", "");
            jo.put("lat", "");
            jo.put("heading", "");
            jo.put("speedvalue", "");
            jo.put("speedunit", "");
            if(StringUtils.isNotEmpty(carstatus.getPositionstop())){
                if(carstatus.getPositionstop().equals(car.getHomestation())){
                    jo.put("ishomestation",1);
                }else{
                    jo.put("ishomestation",0);
                }
            }else{
                jo.put("ishomestation",0);
            }
        }

        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", jo);
        responseData(resultObj.toString(), resp);

    }

    /**
     * 根据用户ID(派件员ID)获取快件列表  0待派件  1已签收
     */
    @RequestMapping(value = "/getDeliveryOrderListByUserId")
    public void getDeliveryOrderListByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getDeliveryOrderListByUserId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");
        String status = jsonObject.getString("status");
        Integer page = jsonObject.getInteger("page");

        //0待派件   1待派件系统分配  2待派件时间预约 3已签收
        //4 问题
        //0已装车  1已取走
        List<DeliveryOrder> listDeliveryOrder = expressManService.getListDeliveryOrderByUserIdAndStatus(userid, status, page, Constants.PAGESIZE);

        JSONArray jsonArray = new JSONArray();
        JSONObject jo = null;


        for (DeliveryOrder order : listDeliveryOrder) {

            jo = new JSONObject();
            ZhiSuoCar car = expressManService.getCarByCarId(order.getCarid());
            String parkareaid = expressManService.getParkareaidByCarId(car.getId());
            String parkAreaName = expressManService.getParkAreaNameById(parkareaid);
            jo.put("carid", car.getId());
            jo.put("carname", car.getName());
            jo.put("parkareaname", parkAreaName);
            jo.put("paymentcode", order.getPaymentcode());
            jo.put("create_time", order.getCreate_time());
            jo.put("mobile", order.getReceiptusermobile());
            jo.put("orderid", order.getId());
            jo.put("isovertime", order.getIsovertime());
            if(order.getStatus()==1 ||order.getStatus()==2 || order.getStatus()==3){
                jo.put("isordertime",1);
            }else{
                jo.put("isordertime",0);
            }
            jo.put("receiptuserorderstarttime",order.getReceiptuserorderstarttime());
            jo.put("receiptuserorderendtime",order.getReceiptuserorderendtime());
            jsonArray.add(jo);
        }
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", jsonArray);
        responseData(resultObj.toString(), resp);

    }





    /**
     * 根据车辆SN码获取车辆信息
     */
    @RequestMapping(value = "/getCarIdBySn")
    public void getCarIdBySn(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getCarIdBySn-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String sn = jsonObject.getString("sn");


        ZhiSuoCar car = expressManService.getCarByQrcode(sn);

        if (car == null) {
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "二维码已失效，请重新扫码");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }

        //0收件车  1派件车  2零售车
        if(car.getType()==1){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            //获取当前时间
            String nowminutes = DateUtil.getMinute(sdf.format(new Date()));
            Integer intnowm = Integer.parseInt(nowminutes);
            if (intnowm >= 55) {
                resultObj.put("error_code", 1);
                resultObj.put("error_msg", "已过投放时间");
                resultObj.put("data", "");
                responseData(resultObj.toString(), resp);
                return;
            }
        }



        if (car == null) {
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "车辆为空");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }

        String parkareaid = expressManService.getParkareaidByCarId(car.getId());
        String parkAreaName = expressManService.getParkAreaNameById(parkareaid);






        JSONObject jo = new JSONObject();
        jo.put("carid", car.getId());
        jo.put("carname", car.getName());
        jo.put("parkareaname", parkAreaName);
        jo.put("parkareaid", parkareaid);

        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", jo);
        responseData(resultObj.toString(), resp);

    }




    /**
     * 根据CarId获取无人车箱子情况-类型情况
     */
    @RequestMapping(value = "/getCarBoxTypeByCarId")
    public void getCarBoxTypeByCarId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getCarBoxTypeByCarId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String carid = jsonObject.getString("carid");

        List<ZhiSuoCarBoxReturnData> listZhiSuoCarBox = expressManService.getListZhiSuoCarBoxTypeInfoByCarId(carid);

        JSONArray jsonArray = new JSONArray();
        JSONObject jo = null;
        if (listZhiSuoCarBox != null && listZhiSuoCarBox.size() > 0) {
            for (ZhiSuoCarBoxReturnData zd : listZhiSuoCarBox) {
                jo = new JSONObject();
                if(zd.getContent().equals("1")){
                    jo.put("boxname", "小箱子 尺寸:30cmx16cm");
                }else if(zd.getContent().equals("2")){
                    jo.put("boxname", "中箱子 尺寸:30cmx21cm");
                }else{
                    jo.put("boxname", "大箱子");

                }

                jo.put("boxcount", zd.getCount());
                jo.put("boxcontent", zd.getContent());
                jsonArray.add(jo);
            }
        } else {
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "此车无箱子可用");
            resultObj.put("data", jsonArray);
            responseData(resultObj.toString(), resp);
            return;
        }

        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", jsonArray);
        responseData(resultObj.toString(), resp);
    }



    /**
     * 确认选择箱子类型，触发开箱及发送短信流程
     */
    @RequestMapping(value = "/confrimCarBoxTypeByCarId")
    public void confrimCarBoxTypeByCarId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("confrimCarBoxTypeByCarId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String carid = jsonObject.getString("carid");
        String boxcontent = jsonObject.getString("boxcontent");
        String userid = jsonObject.getString("userid");
        String paymentcode = jsonObject.getString("paymentcode");
        String receiptusername = jsonObject.getString("receiptusername");
        String receiptusermobile = jsonObject.getString("receiptusermobile");

        List<ZhiSuoCarBox> listhasZhiSuoCarBox=expressManService.getListZhiSuoCarBoxByContent(boxcontent,carid);

        if(listhasZhiSuoCarBox==null ||listhasZhiSuoCarBox.size()==0){
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "箱子不存在");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }

        String boxname=listhasZhiSuoCarBox.get(0).getName();

        ZhiSuoCarBox box = expressManService.getBoxIdByBoxName(boxname);

        if (box == null) {
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "箱子不存在");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }

        String haspaymentcode=expressManService.getHasPaymentCodeByPaymentCode(paymentcode);

        if(StringUtils.isNotEmpty(haspaymentcode)){
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "快递单号已存在,请重新输入单号");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }


        ZhiSuoCar car = expressManService.getCarByCarId(Integer.parseInt(carid));
        List<ZhiSuoCarBox> listZhiSuoCarBox = expressManService.getListZhiSuoCarBoxByCarId(carid);
        DeliveryOrder order = new DeliveryOrder();
        order.setBoxcode(boxname);
        //获取TCP服务器地址
        String tcp_url=apiService.getTcpUrlByTcpCenterUrl("tcp_center_url");
        //下发开箱指令
        String tcpresult = TcpUtil.openDoor(car, order, listZhiSuoCarBox,tcp_url);
        if(StringUtils.isNotEmpty(tcpresult)){
            JSONObject tcpresultjson=JSONObject.parseObject(tcpresult);
            String tcpresultjsonerrorCode=tcpresultjson.getString("errorCode");
            if(tcpresultjsonerrorCode.equals("1")){
                responseErrorData("开门失败，请再试一次", resp);
                return;
            }
        }else{
            responseErrorData("开门失败，请再试一次", resp);
            return;
        }







        //更改载物箱子状态
        expressManService.updateCarBoxIsEmpty(boxname, carid);

        String salemansid = expressManService.getSalemansIdByUserId(userid);
        String paymentcompany = expressManService.getPayMentCompanyById(salemansid);

        //生成派件单
        expressManService.insertNewDeliveryOrderByUserId(carid, box.getId(), box.getCode(), paymentcode, receiptusername, userid, paymentcompany, receiptusermobile);





        //发送短信
        String[] phoneNumbers = new String[]{receiptusermobile};
        String smsjson = SendSmsUtil.sendSmsPutBox(phoneNumbers);
        JSONObject json = JSONObject.parseObject(smsjson);
        //System.out.println("sendSmsPutBox-----------------------:" + json.toString());
        //短信平台返回正确 则代表发送成功
        if (json.getString("result").equals("0")) {
            //记录发送日志
            //System.out.println("sendSmsPutBox-----------------------:" + receiptusermobile);
        } else {
            responseErrorData("开箱失败,请重新再试一次", resp);
        }


        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "派件成功");
        resultObj.put("data", "");
        responseData(resultObj.toString(), resp);
    }



    /**
     * 根据CarId获取无人车箱子情况
     */
    @RequestMapping(value = "/getCarBoxByCarId")
    public void getCarBoxByCarId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getCarBoxByCarId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String carid = jsonObject.getString("carid");

        List<ZhiSuoCarBoxReturnData> listZhiSuoCarBox = expressManService.getListZhiSuoCarBoxInfoByCarId(carid);

        JSONArray jsonArray = new JSONArray();
        JSONObject jo = null;
        if (listZhiSuoCarBox != null && listZhiSuoCarBox.size() > 0) {
            for (ZhiSuoCarBoxReturnData zd : listZhiSuoCarBox) {
                jo = new JSONObject();
                jo.put("boxname", zd.getName());
                jo.put("boxcount", zd.getCount());
                jo.put("boxcontent", zd.getContent());
                jsonArray.add(jo);
            }
        } else {
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "此车无箱子可用");
            resultObj.put("data", jsonArray);
            responseData(resultObj.toString(), resp);
            return;
        }

        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", jsonArray);
        responseData(resultObj.toString(), resp);
    }


    /**
     * 确认选择箱子，触发开箱及发送短信流程
     */
    @RequestMapping(value = "/confrimCarBoxByCarId")
    public void confrimCarBoxByCarId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("confrimCarBoxByCarId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String carid = jsonObject.getString("carid");
        String boxname = jsonObject.getString("boxname");
        String userid = jsonObject.getString("userid");
        String paymentcode = jsonObject.getString("paymentcode");
        String receiptusername = jsonObject.getString("receiptusername");
        String receiptusermobile = jsonObject.getString("receiptusermobile");

        ZhiSuoCarBox box = expressManService.getBoxIdByBoxName(boxname);

        if (box == null) {
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "箱子不存在");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }


        //更改载物箱子状态
        expressManService.updateCarBoxIsEmpty(boxname, carid);

        String salemansid = expressManService.getSalemansIdByUserId(userid);
        String paymentcompany = expressManService.getPayMentCompanyById(salemansid);

        //生成派件单
        expressManService.insertNewDeliveryOrderByUserId(carid, box.getId(), box.getCode(), paymentcode, receiptusername, userid, paymentcompany, receiptusermobile);

        ZhiSuoCar car = expressManService.getCarByCarId(Integer.parseInt(carid));
        List<ZhiSuoCarBox> listZhiSuoCarBox = expressManService.getListZhiSuoCarBoxByCarId(carid);
        DeliveryOrder order = new DeliveryOrder();
        order.setBoxcode(boxname);
        //获取TCP服务器地址
        String tcp_url=apiService.getTcpUrlByTcpCenterUrl("tcp_center_url");
        //下发开箱指令
        String tcpresult = TcpUtil.openDoor(car, order, listZhiSuoCarBox,tcp_url);

        //发送短信
        String[] phoneNumbers = new String[]{receiptusermobile};
        String smsjson = SendSmsUtil.sendSmsPutBox(phoneNumbers);
        JSONObject json = JSONObject.parseObject(smsjson);
        //System.out.println("sendSmsPutBox-----------------------:" + json.toString());
//		短信平台返回正确 则代表发送成功
        if (json.getString("result").equals("0")) {
            //记录发送日志
            System.out.println("sendSmsPutBox-----------------------:" + receiptusermobile);
        } else {
            responseErrorData("开箱失败,请重新再试一次", resp);
        }


        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "派件成功");
        resultObj.put("data", "");
        responseData(resultObj.toString(), resp);
    }


    /**
     * 从req中读取数据
     *
     * @param req
     * @return
     */
    private String getRequestBodyString(HttpServletRequest req) {
        StringBuilder builder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream(), "utf-8"));
            String line;
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
        } catch (IOException e) {
            // e.printStackTrace();
            return null;
        }
        return builder.toString();
    }

    private void responseErrorData(String string, HttpServletResponse resp) throws Exception {
        // TODO Auto-generated method stub
        JSONObject resultObj = new JSONObject();
        resultObj.put("error_code", 1);
        resultObj.put("error_msg", string);
        responseData(resultObj.toString(), resp);
    }

    private void responseData(String string, HttpServletResponse resp) throws Exception {
        // TODO Auto-generated method stub
        responseDate("application/json;charset=UTF-8", string, resp);

    }

    private void responseDate(String contentType, String value, HttpServletResponse resp) throws Exception {
        resp.setContentType(contentType);
        resp.getWriter().write(value);
    }
}
